<template>
	<view class="page">
		<view class="content">
			<view class="main">
				<view class="card">
					<tn-input placeholder="请填写区" :border="false" v-model="form.areaName"></tn-input>
				</view>
				<view class="card">
					<tn-input placeholder="请填写街道" :border="false" v-model="form.streetName"></tn-input>
				</view>
				<view class="card">
					<tn-input placeholder="请填写具体地址" :border="false" v-model="form.address"></tn-input>
				</view>
				<view style="margin: 20rpx 0;font-size: 26rpx;" @click="handleView500m">
					您附近500米内有<text style="color: red;">{{order500m.orderCount}}</text>个地址，共<text
						style="color: red;">{{order500m.dishCount}}</text>单正在拼团，点击查看
				</view>
				<view class="tip">
					因您填写的位置可能会成为明日的公开拼团集合点，此处只可填写具体方位”例如万达广场A门“
				</view>
				<view class="list">
					<block v-for="item in foodList" :Key="item.id">
						<view class="item">
							<image class="cover-img" :src="item.dishImg" mode=""></image>
							<view class="right">
								<view class="title">
									{{item.dishName}}
								</view>
								<view class="title">
									{{item.dishIntroduction}}
								</view>
								<view class="price-box">
									<view class="">
										<view class="price" v-for="(sub,index) in item.specifications" :key="sub.id">
											{{sub.availablePersons}}份及以上单价：￥{{sub.sellPrice}}
										</view>
									</view>
									<tn-number-box v-model="item.bookNum"></tn-number-box>
								</view>
							</view>
						</view>
					</block>
				</view>

				<view>
					<tn-checkbox-group v-model="form.time">
						<tn-checkbox v-for="item in dishTimeSetting" :key="item.id"
							:label="item.type">{{filterDishTimeTypeList(item.type)}}（{{item.timePeriod}})</tn-checkbox>
					</tn-checkbox-group>
					<!-- <tn-checkbox v-model="form.bookLunch" :active-value="1" :inactive-value="0">中午饭（12:00-14:00)</tn-checkbox> -->
					<!-- <tn-checkbox v-model="form.bookDinner" :active-value="1" :inactive-value="0">下午饭（17:50-18:30)</tn-checkbox> -->
				</view>

				<!-- 周餐，月餐 -->
				<view class="tab" style="margin-bottom: 30rpx;">
					<view class="item" :style="{color:form.orderType===item.value?'red':''}" v-for="item in tabList"
						:key="item.value" @click="form.orderType = item.value">
						<text>{{item.label}}</text>
					</view>
				</view>
				<!-- 				<view class="tip" style="color: red;font-size: 26rpx;margin-top: 10rpx;">
					说明：选择后无需预付，每天都会自动统计进订餐名额，价格与上面定价一致
				</view> -->

	<!-- 			<view class="card">
					<tn-input type="number" placeholder="请输入手机号码" :border="false" v-model="form.mobile"></tn-input>
				</view> -->

				<tn-checkbox  checked-shape="circle" v-model="form.headGroup" :active-value="1"
					:inactive-value="0">明天我有空,我愿意成为团长</tn-checkbox>


				<view class="main-wrap">
					<view class="btn" @click="handleCreateOrder">
						点击创建订单
					</view>
				</view>
				<view class="tip" style="color: red;font-size: 26rpx;margin-top: 20rpx;">
					说明：如下方明细内没有您的地址可参与拼团，您可以在这里创建你的地址等待别人加入
				</view>


				<view class="main-list">
					<view class="main-item">
						<view class="main-item-name">
							{{form.areaName?form.areaName:"未选区"}}
							<view class="fixed-text">
								+{{areaCount}}份
							</view>
						</view>
						<block v-if="areaCount > 0">
							<view class="main-item-btn" @click="handleViewStreet">
								点击查看明细
							</view>
							<view class="main-item-tip">
								说明：点击此处可参与您附近创建好的订单
							</view>
						</block>
					</view>
				</view>
			</view>
		</view>

		<!-- 街道列表 -->
		<tn-popup v-model="showStreetPopup" open-direction="bottom" close-btn>
			<view class="popup-wrap">
				<view class="wrap-title">
					<tn-input v-model="streetKeyword" @change="streetKeywordChange" placeholder="请输入地址搜索/支持关键词搜索"></tn-input>
				</view>
				<view class="popup-list">
					<view class="popup-list-item" v-for="item in showStreetOrderList" :key="item.id">
						<view class="popup-list-item-name">
							{{item.streetName}}
							<text class="popup-list-item-name-tip">
								+{{item.count}}份
							</text>
						</view>
						<view class="popup-list-item-btn" @click="handleViewRoad(item)">
							查看明细
						</view>
					</view>
				</view>
			</view>
		</tn-popup>


		<!-- 具体地址 -->
		<tn-popup v-model="showAddressPopup" open-direction="bottom" close-btn>
			<view class="popup-wrap">
				<view class="wrap-title">
					<tn-input v-model="addressKeyword" @change="addressKeywordChange" placeholder="请输入地址搜索/支持关键词搜索"></tn-input>
				</view>
				<view class="popup-list">
					<view class="popup-list-item" v-for="item in showAddressOrderList" :key="item.id">
						<view class="popup-list-item-name">
							{{item.addressName}}
							<text class="popup-list-item-name-tip">
								+{{item.count}}份
							</text>
						</view>
						<view class="popup-list-item-btn" @click="handleGroupMeal(item)">
							点击拼餐
						</view>
					</view>
				</view>
			</view>
		</tn-popup>


		<tn-popup v-model="show500mPopup" open-direction="bottom" close-btn>
			<view class="popup-wrap">
				<view class="wrap-title">
					列表为您附近500m内的自提点
				</view>
				<view class="popup-list">
					<view class="popup-list-item" v-for="(item,index) in order500m.takeList" :key="index">
						<view class="popup-list-item-name">
							{{item.address}}
							<text class="popup-list-item-name-tip">
								距您{{item.distance?.toFixed(0)}}米
							</text>
						</view>
						<view class="popup-list-item-btn" @click="handleGroupMeal500(item)">
							点击拼餐
						</view>
					</view>
				</view>
			</view>
		</tn-popup>





		<!-- 拼餐 -->
		<tn-popup v-model="showFoodPopup" open-direction="bottom" close-btn>
			<view class="popup-wrap">
				<view class="popup-top">
	<!-- 				<view class="card">
						<tn-input :border="false" v-model="joinForm.mobile" placeholder="请输入电话"></tn-input>
					</view> -->
					<!-- <view class="card">
						<tn-input :border="false" v-model="joinForm.bookNum" placeholder="请填写你的份数"></tn-input>
					</view> -->


					<view class="list">
						<block v-for="item in foodAllList" :Key="item.id">
							<view class="item">
								<image class="cover-img" :src="item.dishImg" mode=""></image>
								<view class="right">
									<view class="title">
										{{item.dishName}}
									</view>
									<view class="title">
										{{item.dishIntroduction}}
									</view>
									<view class="price-box">
										<view class="">
											<view class="price" v-for="(sub,index) in item.specifications" :key="sub.id">
												{{sub.availablePersons}}份及以上单价：￥{{sub.sellPrice}}
											</view>
										</view>
										<tn-number-box v-model="item.bookNum"></tn-number-box>
									</view>
								</view>
							</view>
						</block>
					</view>


					<tn-checkbox checked-shape="circle" v-model="joinForm.headGroup" :active-value="1"
						:inactive-value="0">明天我有空,我愿意成为团长</tn-checkbox>
				</view>
				<view class="tip-box">
					<view class="tip-wrap">
						<!-- 			<view class="">
							说明：前2位都可成为团长，第一位为正团长，第二位为备选团长，如第一位用户为空，可直接更换为第二团长
						</view> -->
						<view class="">
							团长佣金说明：2-5份单份0.8元，5-10份单份0.7元
						</view>
						<view class="">
							10份以上单份0.6元，20份以上单份0.5元（无需通知，仅需看餐即可，领完为止）
						</view>
					</view>
				</view>
				<view class="popup-btn">
					<view class="btn" @click="submitJoinOrder">
						立即提交
					</view>
				</view>
			</view>
		</tn-popup>


	</view>
</template>

<script setup>
	import {
		filterDate,
	} from '@/filters';
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from "vue";
	import {
		qqmapsdk,
		filterDishTimeTypeList
	} from '@/const';
	import {
		fetchAreaStreet
	} from '@/api/dish';
	import {
		submitOrder,
		fetchAreaStatistics,
		fetchStreetStatistics,
		fetchRoadStatistics,
		joinGroupAdd,
		getByOrderId,
		fetch500m
	} from '@/api/order';
	import {
		useUser
	} from '@/hooks/user';
	import {
		getFoodList,
		fetchDishTimeSetting
	} from '@/api/dish';



	const emit = defineEmits(['changeTab']);

	// 街道
	const areaCount = ref(0);

	const showStreetPopup = ref(false);
	const streetKeyword = ref('');
	const streetOrderList = ref([]);
	const showStreetOrderList = ref([]);
	const dishTimeSetting = ref([]);


	const getDishTimeSetting = async () => {
		const res = await fetchDishTimeSetting();
		if (res.data) {
			dishTimeSetting.value = res.data;
		}
	}

	// 街道搜索change
	const streetKeywordChange = () => {
		if (streetKeyword.value) {
			showStreetOrderList.value = streetOrderList.value.filter(item => item.streetName.indexOf(streetKeyword.value) > -
				1);
		} else {
			showStreetOrderList.value = streetOrderList.value;
		}
	}



	const handleViewStreet = async () => {
		showStreetPopup.value = true;
		const res = await fetchStreetStatistics({
			areaName: form.areaName
		});
		if (res.data) {
			streetOrderList.value = res.data;
			showStreetOrderList.value = res.data;
		}
	}


	// 街道
	const showAddressPopup = ref(false);
	const addressKeyword = ref('');
	const addressOrderList = ref([]);
	const showAddressOrderList = ref([]);

	// 街道搜索change
	const addressKeywordChange = () => {
		if (addressKeyword.value) {
			showAddressOrderList.value = addressOrderList.value.filter(item => item.addressName.indexOf(addressKeyword
					.value) > -
				1);
		} else {
			showAddressOrderList.value = addressOrderList.value;
		}
	}

	const handleViewRoad = async (item) => {
		showStreetPopup.value = false;
		showAddressPopup.value = true;
		const res = await fetchRoadStatistics({
			areaName: form.areaName,
			streetName: item.streetName
		})
		if (res.data) {
			addressOrderList.value = res.data;
			showAddressOrderList.value = res.data;
		}
	}

	const foodAllList = ref([]);
	const getList = async () => {
		const res = await getFoodList();
		if (res.data) {
			foodAllList.value = res.data.map(item => {
				return {
					...item,
					dishId: item.id,
					bookNum: 0
				}
			});
		}
	}


	// 拼餐
	const joinForm = reactive({
		orderId: "",
		mobile: "",
		bookNum: "",
		headGroup: 0, // 团长 0=否 1=是
		bookList: [],
	})
	const showFoodPopup = ref(false);
	const handleGroupMeal = async (item) => {
		showFoodPopup.value = true;
		showAddressPopup.value = false;
		joinForm.orderId = item.orderIdList[0];
		// const res = await getByOrderId({
		// 	orderId: joinForm.orderId
		// });
		// if (res.data) {
		// 	joinForm.bookList = res.data?.map(item => {
		// 		return {
		// 			...item,
		// 			bookNum: 0,
		// 		}
		// 	})
		// }
	}

	const validateJoin = () => {
		// const currentTimeStamp = new Date().getTime();
		// const targetTimeStamp = new Date(`${filterDate(new Date(),'YYYY/MM/DD')} 18:00:00`).getTime();
		// const noChoose = targetTimeStamp - currentTimeStamp < 0; // 时间差小于0 就不能点餐了
		
		// if (noChoose) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '预定已进入统计期，请明天再试'
		// 	})
		// 	return false;
		// }
		//手机号码
		// if (!joinForm.mobile) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '请输入手机号码'
		// 	})
		// 	return false;
		// }


		const isFood = foodAllList.value.some(item => item.bookNum > 0);
		if (!isFood) {
			uni.showToast({
				icon: 'none',
				title: '请选择份数'
			})
			return false;
		}

		return true;
	}

	const submitJoinOrder = async () => {
		
		
		if (!validateJoin()) return;
		const postData = {
			...joinForm,
			userId: user.value.id,
			bookList: foodAllList.value.map(item => {
				return {
					dishId: item.dishId,
					bookNum: item.bookNum
				}
			}),
			lat: location.lat,
			lng: location.lng,
		}
		const res = await joinGroupAdd(postData);
		if (res.data) {
			uni.showToast({
				icon: 'none',
				title: '拼餐成功'
			})
			emit("changeTab", 'index');
			uni.removeStorageSync('foodList');
		}
	}


	const locationObj = reactive({
		province: "",
		city: "",
	});
	const location = reactive({
		lng: "",
		lat: "",
	})
	const form = reactive({
		userId: "",
		areaName: "",
		streetName: "",
		address: "",
		bookBreakfast: 0,
		bookLunch: 0,
		bookDinner: 0,
		orderType: null, // 1=周餐 2=月餐
		mobile: "", // 预定手机号
		headGroup: 0, // 团长 0=否 1=是
		time: [],
	})


	const [user] = useUser((user) => {
		form.mobile = user.mobile;
		form.userId = user.id;
		joinForm.mobile = user.mobile;
	});

	const foodList = ref([]);
	const tabList = [{
		label: '定周餐',
		value: 1,
	}, {
		label: '定月餐',
		value: 2,
	}];

	onMounted(() => {
		getList();
		getDishTimeSetting();
		getLocation();
		foodList.value = uni.getStorageSync('foodList');
	})



	const getDishOrderSubStatistics = async (areaName) => {
		const res = await fetchAreaStatistics({
			areaName,
		});
		if (res.data) {
			areaCount.value = res.data?.count || 0;
		}
	}

	const init = async ({
		district,
		street,
		street_number
	}) => {
		form.areaName = district;
		form.streetName = street;
		form.address = street_number;
		getDishOrderSubStatistics(form.areaName);
	}




	// 定位
	const getLocation = () => {
		qqmapsdk.reverseGeocoder({
			success(sub) {
				const {
					province,
					city,
					district, // 区
					street, // 街道
					street_number // 道路 
				} = sub.result.address_component;
				location.lng = sub.result.location.lng;
				location.lat = sub.result.location.lat;
				locationObj.province = province;
				locationObj.city = city;
				init({
					district,
					street,
					street_number
				});

				get500m();

			},
			fail(err) {
				console.log('err', err);
			}
		});
	}


	const validate = () => {
		// const currentTimeStamp = new Date().getTime();
		// const targetTimeStamp = new Date(`${filterDate(new Date(),'YYYY/MM/DD')} 18:00:00`).getTime();
		// const noChoose = targetTimeStamp - currentTimeStamp < 0; // 时间差小于0 就不能点餐了
		
		// if (noChoose) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '预定已进入统计期，请明天再试'
		// 	})
		// 	return false;
		// }
		if (form.time.length === 0) {
			uni.showToast({
				icon: 'none',
				title: '早餐/中午饭/下午饭至少选择一个'
			})
			return false;
		}
		if (!foodList.value.length) {
			uni.showToast({
				icon: 'none',
				title: '请选择菜品'
			})
			return false;
		}
		//区
		if (!form.areaName) {
			uni.showToast({
				icon: 'none',
				title: '请输入区'
			})
			return false;
		}

		//街道
		if (!form.streetName) {
			uni.showToast({
				icon: 'none',
				title: '请输入街道'
			})
			return false;
		}
		if (!form.address) {
			uni.showToast({
				icon: 'none',
				title: '请填写具体地址'
			})
			return false;
		}

		//手机号码
		// if (!form.mobile) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '请输入手机号码'
		// 	})
		// 	return false;
		// }

		return true;
	}

	const submitOrderFunc = async (res) => {
		const postData = {
			...form,
			lng: location.lng,
			lat: location.lat,
			bookBreakfast: form.time.includes(1) ? 1 : 0,
			bookLunch: form.time.includes(2) ? 1 : 0,
			bookDinner: form.time.includes(3) ? 1 : 0,
			bookList: foodList.value.map(item => {
				return {
					dishId: item.id,
					bookNum: item.bookNum,
				}
			})
		}
		// 采样地址解析出来的经纬度
		if (res) {
			const resPoint = res.result;
			postData.lat = resPoint.location.lat;
			postData.lng = resPoint.location.lng;
		}

		const resOrder = await submitOrder(postData);
		if (resOrder.data) {
			uni.showToast({
				icon: 'none',
				title: '订餐成功'
			})
			emit("changeTab", 'index');
			uni.removeStorageSync('foodList');
		}
	}

	const handleCreateOrder = async () => {
		if (!validate()) return;
		// const address =
		// 	`${locationObj.province}${locationObj.city}${form.areaName}${form.streetName}${form.address}`;
		// 	console.log('address',address);
		submitOrderFunc();
		// qqmapsdk.geocoder({
		// 	address:decodeURIComponent(address),
		// 	success(res) {
		// 		console.log('res', res);
		// 		submitOrderFunc(res);
		// 	},
		// 	fail(err) {
		// 		console.log('err', err);
		// 		submitOrderFunc();
		// 	}
		// })

	}

	const get500m = async () => {
		const res = await fetch500m({
			userId: user.value.id,
			lng: location.lng,
			lat: location.lat
		})
		if (res.data) {
			order500m.value = res.data;
		}
	}

	const show500mPopup = ref(false);
	const order500m = ref({
		dishCount: 0, // 多少份
		orderCount: 0, // 订单数量
		takeList: []
	});
	const handleView500m = () => {
		show500mPopup.value = true;
	}

	// 500米内拼餐
	const handleGroupMeal500 = async (item) => {
		joinForm.orderId = item.orderId;
		// const res = await getByOrderId({
		// 	orderId: joinForm.orderId
		// });
		// if (res.data) {
		// 	joinForm.bookList = res.data?.map(item => {
		// 		return {
		// 			...item,
		// 			bookNum: 0,
		// 		}
		// 	})
		show500mPopup.value = false;
		showFoodPopup.value = true;
	}
</script>

<style lang="scss" scoped>
	.popup-wrap {
		height: 1200rpx;
		overflow-y: auto;

		.wrap-title {
			padding: 48rpx 100rpx 48rpx 48rpx;
		}

		.card {
			padding: 24rpx;
			border-radius: 24rpx;
			margin-bottom: 24rpx;
			border: 1px solid #ccc;
		}

		.popup-list {
			padding: 24rpx;
			display: flex;
			flex-wrap: wrap;



			&-item {
				margin-right: 20rpx;
				margin-bottom: 60rpx;
				width: 30%;
				display: flex;
				flex-direction: column;
				align-items: center;

				&:nth-child(3n) {
					margin-right: 0;
				}


				&-name {
					position: relative;
					width: 100%;
					font-weight: bold;
					border-radius: 24rpx;
					border: 1px solid #000;
					display: flex;
					justify-content: center;
					align-items: center;
					height: 180rpx;


					&-tip {
						position: absolute;
						color: red;
						font-size: 24rpx;
						top: -40rpx;
						right: 30rpx;
					}
				}

				&-btn {
					margin-top: 12rpx;
					width: 180rpx;
					height: 70rpx;
					text-align: center;
					line-height: 70rpx;
					font-size: 26rpx;
					border-radius: 48rpx;
					color: #fff;
					background-color: #3eb094;
				}
			}
		}

	}

	.page {
		padding-top: 140rpx;
		overflow-y: scroll;
		padding-bottom: 300rpx;

		.content {
			.main {
				padding: 24rpx;

				.title {}

				.card {
					margin-top: 48rpx;
					padding: 10rpx 24rpx;
					border-radius: 24rpx;
					border: 1px solid #ccc;
					margin-bottom: 24rpx;
				}
			}

			.radio-wrap {
				margin-top: 24rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.item {}
			}

			.tab {
				margin-top: 24rpx;
				display: flex;
				align-items: center;
				justify-content: space-evenly;

				.item {
					width: 250rpx;
					height: 70rpx;
					text-align: center;
					line-height: 70rpx;
					color: #fff;
					border-radius: 48rpx;
					background-color: #3eb194;

				}
			}

			.main-wrap {
				margin-top: 48rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.btn {
					padding: 12rpx 48rpx;
					text-align: center;
					line-height: 60rpx;
					color: #fff;
					border-radius: 48rpx;
					background-color: #3eb194;
				}

			}

			.main-list {
				margin-top: 88rpx;

				.main-item {

					width: 200rpx;
					height: 200rpx;

					&-name {
						position: relative;
						height: 60rpx;
						text-align: center;
						line-height: 60rpx;
						margin-bottom: 12rpx;
						border: 1px solid #000;

						.fixed-text {
							position: absolute;
							top: -20rpx;
							right: -80rpx;
							font-size: 24rpx;
							color: red;
						}
					}

					&-btn {
						color: #fff;
						text-align: center;
						line-height: 60rpx;
						font-size: 24rpx;
						padding: 8rpx 12rpx;
						background-color: #3eb194;
						border-radius: 48rpx;
						margin-bottom: 12rpx;
					}

					&-tip {
						width: 600rpx;
						color: red;
						font-size: 26rpx;
					}
				}
			}
		}
	}

	.tip-box {
		padding: 48rpx;
	}

	.popup-top {
		padding: 48rpx 24rpx;
	}

	.tip-wrap {
		font-size: 24rpx;
		color: red;
		padding: 24rpx;
		border: 1px solid red;
		border-radius: 24rpx;
	}

	.popup-btn {
		display: flex;
		align-items: center;
		justify-content: center;

		.btn {
			width: 230rpx;
			height: 80rpx;
			color: #fff;
			text-align: center;
			line-height: 80rpx;
			background-color: #3eb194;
			border-radius: 48rpx;
		}
	}



	.list {
		.item {
			display: flex;
			justify-content: space-between;
			border: 1px solid green;
			border-radius: 16rpx;
			padding: 10rpx;
			margin-bottom: 20rpx;

			.cover-img {
				width: 200rpx;
				height: 200rpx;
				margin-right: 20rpx;
			}

			.right {
				flex: 1;

				.title {
					flex: 1;
					font-size: 24rpx;
					color: #323232;
				}

				.price-box {
					margin-top: 20rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.price {
						color: red;
						font-size: 24rpx;
					}
				}
			}

		}
	}

	.tip {
		font-size: 26rpx;
		color: red;
		margin-bottom: 20rpx;
	}
</style>